package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.result.Code;
import com.itheima.controller.result.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.system.BussinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{uuid}")
    public Result getUser(@PathVariable Integer uuid) {
        System.out.println("get... " + uuid);
        User user = userService.get(uuid);
        Result result;
        if (uuid == 2) {
            throw new BussinessException("查询出错", Code.GET_ERROR);
        }
        if (user != null) {

            result = new Result(Code.GET_OK, user);
        } else {

            result = new Result(Code.GET_ERROR);
        }
        return result;
    }

    @PostMapping()
    public Result save(User user) {
        System.out.println("save... " + user);
        boolean save = userService.save(user);
        Result result = new Result(save ? Code.SAVE_OK : Code.SAVE_ERROR);
        return result;
    }

    @PutMapping()
    public Result update(User user) {
        System.out.println("update... " + user);
        boolean update = userService.update(user);
        Result result = new Result(update ? Code.UPDATE_OK : Code.UPDATE_ERROR);
        return result;
    }

    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid) {
        System.out.println("delete... " + uuid);
        boolean delete = userService.delete(uuid);
        Result result = new Result(delete ? Code.DELETE_OK : Code.DELETE_ERROR);
        return result;
    }

    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page, @PathVariable Integer size) {
        System.out.println("getAll... " + page + " :size " + size);

        PageInfo<User> info = userService.getAll(page, size);
        Result result = new Result(info != null ? Code.GET_OK : Code.GET_ERROR, info);
        return result;
    }

    @PostMapping("/login")
    public Result login(String userName, String password) {
        System.out.println("login... " + userName + " :password " + password);
        User login = userService.login(userName, password);
        Result result = new Result(login != null ? Code.GET_OK : Code.GET_ERROR, login);
        return result;
    }
}
